<template>
  <div>
    <!-- 搜索 -->
    <v-page-search>
      <el-form :inline="true"
               ref="searchForm"
               :model="searchForm"
               solt="search-from">
        <el-form-item prop="customname">
          <el-input v-model="searchForm.customname" placeholder="姓名" style="width: 80px"></el-input>
        </el-form-item>
        <!--<el-form-item>-->
        <!--<el-input v-model="searchForm.source" placeholder="渠道来源" style="width: 120px"></el-input>-->
        <!--</el-form-item>-->
        <el-form-item prop="company">
          <el-input v-model="searchForm.company" placeholder="单位名称" style="width: 120px"></el-input>
        </el-form-item>
        <el-form-item prop="province">
          <el-input v-model="searchForm.province" placeholder="省" style="width: 80px"></el-input>
        </el-form-item>
        <el-form-item prop="city">
          <el-input v-model="searchForm.city" placeholder="地市" style="width: 80px"></el-input>
        </el-form-item>
        <el-form-item prop="channelCreator">
          <el-select v-model="searchForm.channelCreator" filterable collapse-tags style="width: 117px" placeholder="渠道创建人">
            <el-option v-for="item in options.userCreators" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="pricipalName">
          <el-select v-model="searchForm.pricipalName" filterable collapse-tags style="width: 117px" placeholder="渠道跟进人">
            <el-option v-for="item in options.userFollowers" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="sourcetype">
          <el-select v-model="searchForm.sourcetype" style="width: 160px" placeholder="渠道认识途径">
            <el-option v-for="item in options.sourcetype" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="source">
          <el-input v-model="searchForm.source" placeholder="认识途径备注" style="width: 120px"></el-input>
        </el-form-item>
        <el-form-item prop="channelcat">
          <el-select v-model="searchForm.channelcat" style="width: 160px" multiple placeholder="渠道类别">
            <el-option v-for="item in options.channelcat" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="importance">
          <el-select v-model="searchForm.importance" collapse-tags style="width: 105px" placeholder="渠道价值">
            <el-option v-for="item in options.importance" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="rate">
          <el-select v-model="searchForm.rate" collapse-tags style="width: 166px" placeholder="维系状态">
            <el-option v-for="item in options.rate" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="followFrequency">
          <el-select v-model="searchForm.followFrequency" collapse-tags style="width: 110px" placeholder="联系频度">
            <el-option v-for="item in options.channelFollowRate" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="search-but">
        <el-button size="small" type="primary" icon="el-icon-search"　@click="search">搜索</el-button>
        <el-button size="small"　type="info"　icon="el-icon-delete"　@click="clearCondition">清除</el-button>
        <el-button size="small"　icon="el-icon-plus"　@click="addChanelInfo">添加</el-button>
        <el-button size="small"　type="warning"　icon="el-icon-document"　:loading="exprotLoading" @click="exprotChannelInfo">导出</el-button>
      </div>
    </v-page-search>

    <!-- 列表 -->
    <el-table ref="channelTable" :data="tableData" type="expand"　@row-dblclick="editChanelInfo"　@expand-change="showFollowing" @sort-change="sortChange"　v-loading="loading"　border stripe>
      <el-table-column type="expand" size="small" width="40">
        <template slot-scope="props" size="small">
          <el-form label-position="left" size="mini" inline class="demo-table-expand">

          <el-collapse v-model="props.row.activeNames">
            <el-collapse-item name="1">
              <template slot="title">
                <span class="collapse_title">1、基本信息：</span>
              </template>
              <el-row>
                <el-col :span="6">
                  <el-form-item label="姓名">
                    <span>{{ props.row.customname }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="" ></el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="渠道创建人">
                    <span>{{ props.row.channelCreator }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="单位名称">
                    <span>{{ props.row.company }} </span>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="所在部门">
                    <span>{{ props.row.department }} </span>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="职位">
                    <span>{{ props.row.position }} </span>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-collapse-item>

            <el-collapse-item name="2">
              <template slot="title">
                <span class="collapse_title">2、一般信息：</span>
              </template>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="公司简介">
                    <span>{{ props.row.hypro }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="电话" >
                    <span>{{ props.row.tel }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="电子邮件">
                    <span>{{ props.row.email }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="传真">
                    <span>{{ props.row.fax }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="网址">
                    <span>{{ props.row.website }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6">
                  <el-form-item label="省份">
                    <span>{{ props.row.province }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="地市">
                    <span>{{ props.row.city }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="地址">
                    <span>{{ props.row.address }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-collapse-item>

            <el-collapse-item name="3">
              <template slot="title">
                <span class="collapse_title">3、价值信息：</span>
              </template>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="渠道认识途径">
                    <span>{{ props.row.sourceType }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="渠道类别">
                    <span>{{ props.row.channelLables }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item>
                    <el-tooltip slot="label" effect="dark" placement="top-start">
                      <div slot="content">渠道认识途径备注说明</div>
                      <span>认识途径备注<i class="el-icon-question"></i></span>
                    </el-tooltip>
                    <span>{{ props.row.source }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item>
                    <el-tooltip slot="label" effect="dark" placement="top-start">
                      <div slot="content">渠道能力覆盖范围评价</div>
                      <span>能力覆盖范围<i class="el-icon-question"></i></span>
                    </el-tooltip>
                    <span>{{ props.row.channelRegion }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="渠道合作兴趣点">
                    <span>{{ props.row.inmark }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="双方合作共赢点" prop="winwin">
                    <span>{{ props.row.winWin }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6">
                  <el-form-item label="渠道价值">
                    <el-rate v-model="props.row.importance" show-text
                             :texts="['一星潜力','二星潜力','三星潜力','四星潜力','五星潜力']"
                             disabled
                             class="mtop3"
                             :colors="['#99A9BF', '#F7BA2A', '#FF9900']"></el-rate>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-collapse-item>

            <el-collapse-item name="4">
              <template slot="title">
                <span class="collapse_title">4、后续跟进：</span>
              </template>
              <el-row>
                <el-col :span="6">
                  <el-form-item label="跟进人">
                    <span>{{ props.row.pricipalname }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label=""></el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="联系频度建议">
                    <el-tag v-if="props.row.followFrequency" size="small" :type="followFrequencyFlagType(props.row.followFrequency)">{{props.row.followFrequency}}</el-tag>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item>
                    <el-tooltip slot="label" effect="dark" placement="top-start">
                      <div slot="content" v-html="channelRateTexts.join('；<br/>')"></div>
                      <span>维系状态<i class="el-icon-question"></i></span>
                    </el-tooltip>
                    <el-rate v-model="props.row.rate"
                             :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                             :max="6"
                             show-text
                             :texts="channelRateTexts.slice(1,7)"
                             disabled class="mtop3"></el-rate>
                    <span v-if="!props.row.rate">P0：未有沟通，刚记录或则对方无应答状态</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="跟进情况" v-loading="props.row.followLoading">
                    <ul>
                      <li v-for="item,i in props.row.followings">{{props.row.followings.length - i}})
                        <el-tag size="mini" :type="item.typeName === '远程沟通记录' ? 'primary' : 'success'">{{item.typeName}}</el-tag>
                        {{item.followingContent}}
                        <el-tag size="mini" type="info">{{item.followingUser}} {{item.followingTime}}</el-tag>
                      </li>
                    </ul>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-collapse-item>
          </el-collapse>

          <el-row>
            <el-col :span="6">
              <el-form-item label="记录添加">
                <span>{{ props.row.creatoruser }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="添加时间">
                <span>{{ props.row.creationtime.replace('T',' ') }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="记录更新">
                <span>{{ props.row.lastmodifieruser }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="更新时间">
                <span>{{ props.row.lastmodificationtime.replace('T',' ') }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          </el-form>
        </template>
      </el-table-column>
      <el-table-column prop="customname" sortable="custom" label="姓名" align="center" width="60">
        <template slot-scope="props">
          <el-popover placement="bottom"
                      trigger="hover"
                      :content="props.row.customname">
            <span slot="reference"
                  class="table-overflow-hidden">{{props.row.customname}}</span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="tel"　label="电话"　align="center" width="95">
        <template slot-scope="props">
          <el-popover placement="bottom"　trigger="hover"　:content="props.row.tel">
            <span slot="reference"　class="table-overflow-hidden">{{props.row.tel}}</span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="position"　label="职位"　align="center"　width="70">
        <template slot-scope="props">
          <el-popover placement="bottom"　trigger="hover"　:content="props.row.position">
            <span slot="reference"　class="table-overflow-hidden">{{props.row.position}}</span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="company" sortable="custom"　label="单位名称"　align="center" width="130" >
        <template slot-scope="props">
          <el-popover placement="bottom" trigger="hover" :content="props.row.company">
            <span slot="reference" class="table-overflow-hidden">{{props.row.company}}</span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="province" sortable="custom" label="省份" align="center" width="55">
        <template slot-scope="props">
          <el-popover placement="bottom" trigger="hover" :content="props.row.province">
            <span slot="reference" class="table-overflow-hidden">{{props.row.province}}</span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="city" sortable="custom" label="地市" align="center" width="55">
        <template slot-scope="props">
          <el-popover placement="bottom" trigger="hover" :content="props.row.city">
            <span slot="reference" class="table-overflow-hidden">{{props.row.city}}</span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="sourceType" sortable="custom" label="认识途径" align="center" width="95" >
        <template slot-scope="props">
          <el-popover placement="bottom" trigger="hover" :content="!props.row.sourceType?props.row.source:props.row.sourceType">
            <span slot="reference" class="table-overflow-hidden">{{!props.row.sourceType?props.row.source:props.row.sourceType}}</span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column sortable label="渠道类别" align="center" width="140">
        <template slot-scope="props">
          <el-popover placement="bottom" trigger="hover" :content="props.row.channelLables">
            <span slot="reference" class="table-overflow-hidden">
              {{props.row.channelLables}}
            </span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="followFrequency" sortable="custom"　label="联系频度"　align="center" width="85">
        <template slot-scope="props">
          <el-tag v-if="props.row.followFrequency" size="small" :type="followFrequencyFlagType(props.row.followFrequency)">{{props.row.followFrequency}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="importance" sortable="custom" label="渠道价值" align="center" width="125">
        <template slot-scope="props">
          <el-rate v-model="props.row.importance" disabled :colors="['#99A9BF', '#F7BA2A', '#FF9900']">
          </el-rate>
        </template>
      </el-table-column>
      <el-table-column prop="rate" sortable="custom" label="维系状态" align="center" width="125">
        <template slot-scope="props">
          <span style="float: left">&nbsp;{{channelRateValue(props.row.rate)}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="pricipalname" sortable="custom" label="跟进人" align="center" width="70" />
      <el-table-column  label="最新跟进情况" align="center">
        <template slot-scope="props">
          <el-popover placement="bottom" trigger="hover" :content="props.row.followingContent" style="float:left;padding: 0 3px">
            <span slot="reference" class="table-overflow-hidden">
              <el-tag size="small" v-if="props.row.followingType" :type="props.row.followingType === 2 ? 'primary' : 'success'">{{flowwingFlag(props.row.followingType)}}</el-tag>
              {{props.row.followingContent}}
            </span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="followingTime" sortable="custom"　label="更新时间"　align="center"　width="90">
        <template slot-scope="props">
          <span>{{props.row.lastUpdateTime}}</span>
        </template>
      </el-table-column>
      <!--<el-table-column label="操作"　align="center"　width="80">-->
        <!--<template slot-scope="scope">-->
          <!--<el-button　size="mini"　type="danger" plain　@click="editChanelInfo(scope.row)">跟进</el-button>-->
        <!--</template>-->
      <!--</el-table-column>-->
    </el-table>

    <!-- 分页 -->
    <el-pagination layout="total, sizes, prev, pager, next, jumper"　:total="pagging.total"　:current-page="pagging.currentPage"　:page-sizes="pagging.sizes"　@size-change="sizeChange"　@current-change="pageChange">
    </el-pagination>

    <!-- 项目信息 -->
    <channel-dailog @close-dialog="onClose" @reflash-top-table="getTableData"></channel-dailog>

    <iframe ref="ifile" style="display:none"></iframe>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import _ from 'lodash'
import Bus from '@/utils/bus'
import Moment from 'moment'
import { getLists, exprotChannel, getChannelfollowingAll } from '@/api/channel'
import ChannelDailog from './detail/channel-dailog'
import PopoverView from './plant/popover-view-completed'
import Explain from './explain/explain'
import { computeState, sumState } from '@/utils/bitcompute'
import { Message } from 'element-ui'

export default {
  data() {
    return {
      loading: false,
      exprotLoading: false,
      dialogVisible: false,
      explainDialogVisible: false,
      // 筛选条件
      searchForm: {
        customname : '',
        source: '',
        type: '',
        channelCreator: '',
        pricipalName: '',
        province: '',
        city: '',
        company: '',
        rate: '',
        sourcetype:'',
        source:'',
        importance:'',
        channelcat:'',
        followFrequency: ''
      },
      // 选项
      options: {
        // 类别
        type: [],
        // 链接评价
        rate: [],
        // 渠道类别
        channelcat:[],
        importance: [],
        sourcetype:[],
        userCreators:[],
        userFollowers:[],
        channelFollowRate:[]
      },
      // 表格数据
      tableData: [],
      // 分页属性
      pagging: {
        total: 0,
        currentPage: 1,
        pageSize: 50,
        sizes: [50, 100, 300, 500, 1000]
      },
      order:{}
    }
  },
  computed: {
    ...mapGetters([
      'userInfo',
      'appEnum',
      'users',
      'channelRateTexts'
    ])
  },
  mounted() {
    this.initEnum()
    this.getUsers().then(data => {
      this.options.userCreators  = _.union([{ value: null, label: '所有创建人'}],data);
      this.options.userFollowers  = _.union([{ value: null, label: '所有跟进人'}],data);
    })
    this.search()
  },
  methods: {
    ...mapActions([
      'getUsers'
    ]),

    channelRateValue(v) {
      var result = _.find(this.appEnum.channelRate, o => o.value == v )
      return result && result.label || ''
    },

    sortChange({column, prop, order}) {
      this.order = {prop,order}
      this.getTableData()
    },

    followFrequencyFlagType(type){
      switch(type)
      {
        case '每月一次':
          return 'danger'
          break
        case '每月两次':
          return 'success'
          break
        case '每季一次':
          return 'warning'
          break
        case '无需联系':
          return 'info'
          break
      }
    },

    flowwingFlag(type){
      var data =  _.filter(this.appEnum.channelFollowingType, d=> d.value == type)
      var result = data && data[0] && data[0].label || '';
      return result.substring(0,2)
    },

    initEnum(){
      // this.options.type = _.union([{ value: null, label: '全部'}], this.appEnum.channelType);
      this.options.rate =_.union([{ value: null, label: '所有维系状态'}],this.appEnum.channelRate);
      this.options.importance = _.union([{ value: null, label: '所有价值'}],this.appEnum.channelImportance);
      this.options.sourcetype = _.union([{ value: null, label: '所有认识途径'}],this.appEnum.channelSourceType);
      this.options.channelFollowRate = _.union([{ value: null, label: '所有联系频度'}],this.appEnum.channelFollowRate);
      this.options.channelcat = this.appEnum.channelType
    },

    search() {
      this.pagging.currentPage = 1
      this.$refs.channelTable.clearSort()
      this.order = {}
      this.getTableData()
    },
    // 请求渠道信息
    getTableData() {
      this.loading = true
      this.searchForm.channeltype = sumState(this.searchForm.channelcat)

      // var obj = computeState(this.appEnum.channelType, this.searchForm.channeltype)

      const params = _.assignIn({}
        ,this.searchForm
        ,{
        pageIndex: this.pagging.currentPage,
        pageSize: this.pagging.pageSize
        }
        ,this.order)

      // 请求数据
      getLists(params).then(res => {
        if (res.data.success) {
          const result = res.data.data
          result.data.map((opt)=>{
            var time = opt.followingTime?opt.followingTime:opt.lastmodificationtime;
            opt.lastUpdateTime =  Moment(time).format('YYYY-MM-DD'); // HH:mm:ss
            var channelCat = computeState(this.appEnum.channelType, opt.channelType)
            opt.channelcat = channelCat.values
            opt.channelLables = channelCat.labels
          })

          this.tableData = result.data
          this.pagging.total = result.totalCount
          this.pagging.currentPage = result.pageIndex
          this.pagging.pageSize = result.pageSize
          this.loading = false
        }
      })
    },

    // 每页显示条数变更新
    sizeChange(size) {
      this.pagging.pageSize = size
      this.getTableData()
    },
    // 跳转到页面
    pageChange(curPage) {
      this.pagging.currentPage = curPage
      this.getTableData()
    },
    // 清除筛选条件
    clearCondition() {
      this.$refs.searchForm.resetFields()
      this.search()
    },

    // dailog关闭/取消回调
    onClose() {
      this.getTableData()
    },
    // 新增项目信息
    addChanelInfo() {
      Bus.$emit('open-channel-dailog', null)
    },
    // // 编辑项目信息
    editChanelInfo(row) {
      // row.channelcat = [] //select控件不能这样传惨，在详细界面会出错，要传继承vm的原型
      Bus.$emit('open-channel-dailog', row)
    },

    showFollowing(row) {
      if(row.expending) {
        row.expending = false
        return;
      }
      row.expending = true;
      row.followLoading = true;
      row.activeNames = ['1','2','3','4']
      // 请求数据
      getChannelfollowingAll({ChannelId:row.id}).then(res => {
          if (res.data.success) {
            const result = res.data.data
            result.map((opt)=>{
              opt.followingtime =  Moment(opt.followingtime).format('YYYY-MM-DD HH:mm:ss'); // HH:mm:ss
            })
            row.customname = row.customname + ' '; //这是 vue 的 bug，要更新下其他字段，否则然不能更新
            row.followings = result;
            row.followLoading = false;
            row.customname = _.trim(row.customname)
          }
        }
      )
    },
    // 导出信息
    exprotChannelInfo() {
      this.exprotLoading = true
      const params = _.assignIn({}, this.searchForm, {})

      exprotChannel(params).then(res => {
        this.exprotLoading = false
        if (res.data.success) {
          // window.open('http://' + res.data.data)
          this.$refs.ifile.src = 'http://' + res.data.data

 /*         var form = document.createElement("form")
          form.method = 'get'
          form.action = 'http://' + res.data.data
          document.body.appendChild(form)
          form.submit()
          document.body.removeChild(form)
          form.remove()*/
        }else{
          Message({
            message: res.data.data,
            type: 'error',
            duration: 3 * 1000
          })

        }
      }).catch(data=>{
        this.exprotLoading = false
        Message({
          message: data,
          type: 'error',
          duration: 3 * 1000
        })
      })


    }
  },
  components: {
    ChannelDailog,
    PopoverView,
    Explain
  }
}
</script>

<style lang="scss">
  .mtop3{
    margin-top: 5px;
  }
  .collapse_title{
    font-style:italic;
    font-weight:bold
  }
</style>
